/**
 * Copyright (c) Huawei Technologies Co., Ltd. 1987-2021. All rights reserved.
*/

package com.gitee.fufu669.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangfupeng
 */
public class CacheXmlUtil {

    /**
     * TODO
    */
    public static final Logger logger = LoggerFactory.getLogger(CacheStringUtils.class);

    /**key不能是纯数字，必须是以字母开头的。否则会报错*/
    /**
     * TODO
    */
    public static String mapToXml(Map<String, String> data) throws Exception {
        // TODO
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        // TODO
        DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
        // TODO
        org.w3c.dom.Document document = documentBuilder.newDocument();
        // 创建
        org.w3c.dom.Element root = document.createElement("xml");
        // TODO
        document.appendChild(root);
        // 遍历
        for (String key: data.keySet()) {
            // 字符串赋值
            String value = data.get(key);
            // 判断是否是空
            if (value == null) {
                // 赋值
                value = "";
            }
            // TODO
            value = value.trim();
            // 创建
            org.w3c.dom.Element filed = document.createElement(key);
            // 创建
            filed.appendChild(document.createTextNode(value));
            // TODO
            root.appendChild(filed);
        }
        // TODO
        TransformerFactory tf = TransformerFactory.newInstance();
        // TODO
        Transformer transformer = tf.newTransformer();
        // 创建
        DOMSource source = new DOMSource(document);
        // TODO
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        // TODO
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        // 创建
        StringWriter writer = new StringWriter();
        // 创建
        StreamResult result = new StreamResult(writer);
        // TODO
        transformer.transform(source, result);
        // 替换
        String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
        // 尝试下面的代码
        try {
            // 关闭
            writer.close();
        }
        // 捕捉异常
        catch (Exception ex) {
        }
        // 返回
        return output;
    }

    /**
     * TODO
    */
    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        // 尝试下面的代码
        try {
            // 创建
            Map<String, String> data = new HashMap<String, String>();
            // TODO
            DocumentBuilder documentBuilder = newDocumentBuilder();
            // 创建
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            // 转换
            Document doc = documentBuilder.parse(stream);
            // TODO
            doc.getDocumentElement().normalize();
            // TODO
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            // 遍历
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                // TODO
                Node node = nodeList.item(idx);
                // 判断
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    // TODO
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    // 塞入
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            // 尝试下面的代码
            try {
                // 关闭
                stream.close();
            // 捕捉异常
            } catch (Exception ex) {
                // 抛出异常
                throw new RuntimeException("xmlToMap error: " + strXML + ex.getMessage(), ex);
            }
            // 返回
            return data;
        // 捕捉异常
        } catch (Exception ex) {
            // 抛出异常
            throw new RuntimeException("xmlToMap error: " + strXML + ex.getMessage(), ex);
        }

    }

    /**
     * TODO
    */
    public static Document newDocument() throws ParserConfigurationException {
        // 返回
        return newDocumentBuilder().newDocument();
    }

    /**
     * TODO
    */
    public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
        // TODO
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        // TODO
        documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        // TODO
        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        // TODO
        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        // TODO
        documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        // TODO
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        // TODO
        documentBuilderFactory.setXIncludeAware(false);
        // TODO
        documentBuilderFactory.setExpandEntityReferences(false);
        // 返回
        return documentBuilderFactory.newDocumentBuilder();
    }

}
